package com.why.cachecloud.service.alert.impl;

import com.why.cachecloud.dao.WarnConfigDao;
import com.why.cachecloud.entity.WarnConfig;
import com.why.cachecloud.service.alert.WarnConfigService;
import com.why.cachecloud.service.alert.WarnType;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
public class WarnConfigServiceImpl implements WarnConfigService {

    List<WarnConfig> allConfig = Collections.emptyList();

    @Resource
    private WarnConfigDao warnConfigDao;

    @PostConstruct
    public void init() {
        initConfig();
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(this::initConfig, 30, 30, TimeUnit.SECONDS);
    }

    private void initConfig() {
        allConfig = warnConfigDao.getAll();
    }

    @Override
    public WarnConfig queryConfig(long appId, WarnType type) {
        WarnConfig warnConfig = allConfig.stream().filter(ac -> ac.getAppId().equals(appId) && ac.getWarnType().equals(type.name())).findFirst().orElse(null);
        if (warnConfig != null) {
            return warnConfig;
        }
        return appId == 0L ? null : allConfig.stream().filter(ac -> ac.getAppId() == 0L && ac.getWarnType().equals(type.name())).findFirst().orElse(null);
    }
}